import React from 'react'
import { Button, message } from 'antd'

import $http from '../../Utils/request';
import storage from '../../Utils/storage';
import store from '../../store'
import { connect } from 'react-redux'
import { setCartNum } from '../../actions/cartAction'

//创建请求头文件
let config = {}
if(storage.get("token") !== null){
  config = {
    headers:
      {'Content-Type': 'application/json',
        'token':storage.get("token").data
      }
  }
}else{
  config = {
    headers:
      {'Content-Type': 'application/json'
      }
  }
}

class ProductDetailBut extends React.Component {
  constructor (props) {
    super(props);
    this.state={
      cartNums : 0
    }
  }

  /**
   * 购物车
   */
  addShoppingCart = () => {
    const { dispatch } = this.props
    //拿到用户信息
    storage.get("token");
    //数据处理
    const data = {
      productId:this.props.data.productId,
      shopInfoId:this.props.data.shopInfoId,
      quantity:this.props.dataNum,
      sku:this.props.data.sku,
      branchName:this.props.data.shopcompany
    }
    //准备数据向后台进行请求
    $http.post("http://localhost/mall-basic-service/basic/shoppingCart/saveBasicShoppingCart",data,config).then((response)=>{
      if(response.data.data === "新增成功"){
        //请求查询接口
        //请求后台查询数据
        $http.get("http://localhost/mall-basic-service/basic/shoppingCart/queryShoppingCartToUserId",config).then((response)=>{
          dispatch(setCartNum(response.data.data.length))
          message.success("已添加");
        })
      }
    })
  }

  /**
   * 购买
   */
  buyProductInfo =() =>{
    const {carts} = this.props
    store.dispatch({type:"addNum",data: this.props.dataNum+1});
    this.setState({
      cartNums: carts
    })
  }
  render () {
    return (
      <div>
        <span>{}</span>
        <span className={'detailsButtonAddDiv'}><Button type="primary" onClick={this.addShoppingCart}>加入购物车</Button></span>
        <span className={'detailsBuyDiv'}><Button type="primary" onClick={this.buyProductInfo}>购买</Button></span>
      </div>
    )
  }
}

const mapStateToProps = (state) =>{
  return {
    carts: state.get('cartNum')
  }
}

export default connect(mapStateToProps)(ProductDetailBut)





